package com.sneaker.shower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.request.WxPayDownloadFundFlowRequest;
import com.github.binarywang.wxpay.bean.result.WxPayFundFlowResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.sneaker.shower.entity.domain.WxFundFlowInfoDO;
import com.sneaker.shower.entity.dto.DownloadBillReqDTO;
import com.sneaker.shower.mapper.WxFundFlowMapper;
import com.sneaker.shower.mapstruct.WxFundFlowMapStruct;
import com.sneaker.shower.service.WxFundFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Hechangjian
 * @version 1.0
 * @className WxFundFlowServiceImpl
 * @date 2019/11/19 18:00
 * @description
 * @program bath
 */
@Service
public class WxFundFlowServiceImpl extends ServiceImpl<WxFundFlowMapper, WxFundFlowInfoDO> implements WxFundFlowService {

    private final WxPayService wxPayService;

    @Autowired
    public WxFundFlowServiceImpl(WxPayService wxPayService) {
        this.wxPayService = wxPayService;
    }

    @Override
    public void downloadFundFlow(DownloadBillReqDTO reqDTO) {
        LocalDate date = reqDTO.getStartDate();
        for (long i = 0; i < reqDTO.getEndDate().toEpochDay() - reqDTO.getStartDate().toEpochDay(); i++) {
            String dateStr = date.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            WxPayDownloadFundFlowRequest request = WxPayDownloadFundFlowRequest.newBuilder()
                    .billDate(dateStr)
                    .accountType("Basic")
                    .build();
            try {
                WxPayFundFlowResult wxPayFundFlowResult = wxPayService.downloadFundFlow(request);
                List<WxFundFlowInfoDO> list = wxPayFundFlowResult.getWxPayFundFlowBaseResultList().stream().map(f -> {
                    WxFundFlowInfoDO wxFundFlowInfoDO = WxFundFlowMapStruct.INSTANCE.flow2DO(f);
                    wxFundFlowInfoDO.setGuid(IdWorker.getId());
                    return wxFundFlowInfoDO;
                }).collect(Collectors.toList());
                this.remove(new LambdaQueryWrapper<WxFundFlowInfoDO>().ge(WxFundFlowInfoDO::getBillingTime, date.atTime(LocalTime.MIN))
                        .le(WxFundFlowInfoDO::getBillingTime, date.atTime(LocalTime.MAX)));
                this.saveBatch(list);
            } catch (WxPayException e) {
                e.printStackTrace();
            }
            date = date.plusDays(1);
        }
    }
}
